#include "stdafx.h"
#include "websocketserver.hxx"
#include "websocketsession.hxx"

#include <boost/bind.hpp>
#include <boost/thread.hpp>

using namespace WSS;
//-------------------------------------------------------
WebSocketServer::WebSocketServer(unsigned int port, unsigned int workers)
:mAcceptor(mIoService, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))
,mWorkers(workers)
,mPort(port)
{
}

WebSocketServer::~WebSocketServer()
{
}
//-------------------------------------------------------
//public
void WebSocketServer::start()
{
   asyncAccept();

   internalRun();
}
//-------------------------------------------------------
//private
void WebSocketServer::internalRun()
{
   boost::thread_group workers;

   for (unsigned int i = 0; i < mWorkers; ++i)
   {
      workers.create_thread(boost::bind(&boost::asio::io_service::run, &mIoService));
   }

   workers.join_all();
}

//private
void WebSocketServer::asyncAccept()
{
   WebSocketSessionPtr wssPtr(new WebSocketSession(mIoService, mPort));
   if (wssPtr)
   {
      mAcceptor.async_accept(wssPtr->getSocket(),
         boost::bind(&WebSocketServer::handleAccept,
         this,
         wssPtr,
         boost::asio::placeholders::error
         ));
   }
}

//private
void WebSocketServer::handleAccept(WebSocketSessionPtr webSockSession, const boost::system::error_code& error)
{
   if (!error && webSockSession)
   {
      webSockSession->start();

      asyncAccept();
   }
}
//-------------------------------------------------------